

import sys
import os
sys.path.append(os.path.abspath(os.curdir))

import tensorflow as tf
import mnist_data
# import mnistdata

# mnist = mnistdata.read_data_sets("data", one_hot=True, reshape=False)

print "tf start"
x = tf.placeholder("float", [None, 784])
# x = tf.placeholder("float", [None, 28, 28, 1])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# XX = tf.reshape(x, [-1, 784])

y = tf.nn.softmax(tf.matmul(x, W) + b)
# y = tf.nn.softmax(tf.matmul(XX, W) + b)

y_ = tf.placeholder("float", [None, 10])

cross_entropy = -tf.reduce_sum(y_*tf.log(y))

train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

init = tf.initialize_all_variables()

print "start and init session"

sess = tf.Session()
sess.run(init)

# sess = tf.InteractiveSession()
# sess.run(tf.initialize_all_variables())




def train_(n):
	for i in range(n):
		# print "train ", i
		batch_xs, batch_ys = mnist_data.train.next(100)
		# batch_xs, batch_ys = mnist.train.next_batch(100)
		sess.run(train_step, feed_dict={x: batch_xs, y_ : batch_ys})
		del batch_xs
		del batch_ys

def check():
	correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
	accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
	test_xs, test_ys = mnist_data.test.next(10000)
	# test_xs = mnist.test.images
	# test_ys = mnist.test.labels
	# print sess.run(tf.argmax(y, 1), feed_dict={x: test_xs, y_: test_ys})
	print sess.run(accuracy, feed_dict={x: test_xs, y_: test_ys})


# def out_img(batch_xs, k=None):
# 	for x1 in batch_xs:
# 		print len(x1)
# 		for x2 in x1:
# 			for x3 in x2:
# 				for x4 in x3:
# 					if k == None:
# 						print "%4d"%(int(x4*255)),
# 					else:
# 						print "%4d"%(int(x4)),
# 					# print "%.8f"%x4,
# 			print ""


# def test():
# 	batch_xs, batch_ys = mnist.train.next_batch(1)
# 	print batch_ys[0]
# 	out_img(batch_xs)	
# 	batch_xs, batch_ys = mnist_data.train.next(1)
# 	print batch_ys[0]
# 	out_img(batch_xs)
# 	# print batch_xs[0][14][14][0]

wrater = tf.summary.FileWriter("gg", graph_def=sess.graph_def)

def main():
	for i in xrange(2):
		train_(100)
		print "train %d finish: "%(i * 100), 
		check()
	sess.close()
	wrater.close()

if __name__ == '__main__':
	main()
	# test()

